package com.ytjj.quartz.service;

import com.alibaba.fastjson.JSON;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.DateTimeUtil;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.mapper.ReturnGoodsMapper;
import com.ytjj.qmyx.mall.model.ExpressOrders;
import com.ytjj.qmyx.mall.model.OrdersInfo;
import com.ytjj.qmyx.mall.model.ReturnGoods;
import com.ytjj.qmyx.users.client.AdminClient;
import com.ytjj.quartz.dao.ReturnGoodsDao;
import com.ytjj.quartz.enums.OrderStatusEnums;
import com.ytjj.quartz.model.ReturnOrdersResponse;
import com.ytjj.quartz.model.YxReturnGoods;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author jiawei
 * @date 2023年04月12日 16:45
 * @describe
 */
@Service
@Slf4j
public class ReturnGoodsOtherService {
    @Resource
    private ReturnGoodsDao returnGoodsDao;
    @Resource
    @Lazy
    private ReturnGoodsService returnGoodsService;
    @Resource
    private AdminClient adminClient;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;

    /**
     * 更新销售渠道和供应链售后单状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBankerStatusByAfterType(ReturnGoods returnGoods){
        Integer integer = returnGoodsDao.updateBankerStatusByAfterType();
        //是否执行正常 true-正常
        boolean resultMark = true;
        if(integer > 0){
            try {
                YxReturnGoods yxReturnGoods = new YxReturnGoods();
                yxReturnGoods.setServiceNo(returnGoods.getServiceNo());
                yxReturnGoods.setBankerStatus(2);
                yxReturnGoods.setStatus(4);
                yxReturnGoods.setBankerApplyTime(new Date());
                String s = returnGoodsService.updateReturnGoods(yxReturnGoods);
                CommonResult commonResult = com.gexin.fastjson.JSONObject.parseObject(s, CommonResult.class);
                if (null == commonResult || 200 != commonResult.getCode()) {
                    resultMark = false;
                }
            } catch (Exception e) {
                resultMark = false;
                log.error("售后类型为【退款】的售后单，供应商超时审核-默认同意,代码执行出错!{}",e);
            }finally {
                if(!resultMark){
                    FeiShuUtil.sendMsg("【退款】类型的售后单，供应商超时-默认同意,代码执行出错! 子订单Id："+returnGoods.getOrdersInfoId());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            }
        }
    }


    /**
     * 针对【仅退款】的售后
     * @param response 销售端售后订单信息
     * @param eos 供应链物流
     * @return void
     */
    @Transactional(rollbackFor = Exception.class)
    public void verifyInvalidForOnlyRefund(ReturnOrdersResponse response, ExpressOrders eos) {
        if (null != eos) {
            //快递已签收,不用isCheck,checkTime判断是因为之前的旧数据这些字段不准确
            if (Arrays.asList("3", "301", "302", "303", "304").contains(eos.getStatus().toString())) {
                String serviceDesc = "包裹已被客户签收，系统自动审核失败,如有疑问请联系客服，审核时间："+DateTimeUtil.TimeToStr(new Date());
                //订单需要回到原状态，由于redis不是同一个数据库，所以订单的原状态要从admin服务获取
                CommonResult statusResult = adminClient.getRedisString("return:good:orderInfoStatus" + response.getOrderInfoId());
                if (statusResult.getCode() != 200 || null == statusResult.getData()) {
                    FeiShuUtil.sendMsg(String.format("【仅退款】订单回到原状态是失败，子订单id：%s，原状态不存在！",response.getOrderInfoId()));
                    return;
                }
                String resText = eos.getResText();
                if(StringUtils.isEmpty(resText)){
                    return;
                }
                QueryTrackResp queryTrackResp = JSON.parseObject(resText, QueryTrackResp.class);
                if(null == queryTrackResp){
                    return;
                }
                List<QueryTrackData> data = queryTrackResp.getData();
                if(CollectionUtils.isEmpty(data)){
                    return;
                }
                //签收时间是否超7天
                QueryTrackData queryTrackData = data.get(0);
                boolean timeOut = DateTimeUtil.isTimeOut(DateTimeUtil.StrToTime(queryTrackData.getFtime()), 7 * 24);
                if(timeOut){
                    boolean b = data.stream().anyMatch(e -> isReject(e.getContext()));
                    if(b){
                        return;
                    }
                    Integer integer = returnGoodsService.rollbackOrderStatus(response.getOrderInfoId(), statusResult.getData().toString(), response.getServiceNo(),serviceDesc);
                    int i = returnGoodsDao.refuseOnlyRefund(response.getServiceNo(),serviceDesc);
                    if (integer == 0 || i == 0) {
                        log.info("订单回到原状态出错！==>{}", JSON.toJSONString(response));
                        throw new ApiException("订单回到原状态出错！");
                    }
                    log.info("=======包裹已被客户签收，订单{}已回到原状态=======",response.getOrderInfoId());
                }
            }

//            // todo 退回已签收 (由于物流不准确，暂时只能通过人工处理)
//            if (null != eos.getStatus() && 4 == eos.getStatus()) {
//                String serviceDesc = "包裹已退回商家签收，系统自动通过审核，审核时间："+ DateTimeUtil.TimeToStr(new Date());
//                //售后修改成待退款
//                returnGoodsDao.agreeOnlyRefund(response.getOrderInfoId(),serviceDesc);
//                //售后订单状态同步到供应链
//                YxReturnGoods yxReturnGoods = new YxReturnGoods();
//                yxReturnGoods.setServiceNo(response.getServiceNo());
//                yxReturnGoods.setStatus(4);
//                yxReturnGoods.setUpdateTime(new Date());
//                yxReturnGoods.setServiceDesc(serviceDesc);
//                String s = returnGoodsService.updateReturnGoods(yxReturnGoods);
//                CommonResult commonResult = com.gexin.fastjson.JSONObject.parseObject(s, CommonResult.class);
//                if (null == commonResult || 200 != commonResult.getCode()) {
//                    throw new ApiException("售后状态同步到供应链出错！");
//                }
//                log.info("=======包裹已退回商家签收，售后单{}已设置成待退款=======",response.getOrderInfoId());
//            }
        }
    }

    /**
     * 是否已拒收
     * @param content 最新的物流信息
     * @return boolean true 可能已退回，false 未退回
     */
    public boolean isReject(String content) {
        if(StringUtils.isEmpty(content)){
            return false;
        }
        List<String> baseContent = new ArrayList<>();
        baseContent.add("拒收");
        baseContent.add("退回");
        baseContent.add("拒签");
        boolean result = baseContent.stream().anyMatch(e -> content.contains(e));
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public void verifyInvalid(ReturnInvalidResponse response) {
        try {
            //由于redis不是同一个数据库，所以订单的原状态要从admin获取
            CommonResult result = adminClient.getRedisString("return:good:orderInfoStatus" + response.getOrdersInfoId());
            if (result.getCode() != 200) {
                return;
            }
            int count = returnGoodsDao.updateInvalidStatus(response.getId());
            //是否更新成功
            if (count == 0) {
                //再查一遍售后是否已是7关闭状态
                ReturnGoods returnGoods = returnGoodsMapper.selectByPrimaryKey(response.getId());
                //当前售后已不是关闭状态，则订单不能回到原状态
                if (returnGoods.getStatus() != 7) {
                    FeiShuUtil.sendMsg(String.format("当前售后单%s已不是失败状态7，被哪里改成了：%s",returnGoods.getServiceNo(),returnGoods.getStatus()) );
                    return;
                }
            }
            //
            String orderInfoStatus = result.getData().toString();
            if (StringUtils.isEmpty(orderInfoStatus) || "6".equals(orderInfoStatus)) {
                if (com.alibaba.excel.util.StringUtils.isEmpty(orderInfoStatus) || OrderStatusEnums.REFUND.getValue().equals(orderInfoStatus)) {
                    OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(response.getOrdersInfoId());
                    //Redis保存的是售后状态，撤销了需要回到原状态了。
                    if (!com.alibaba.excel.util.StringUtils.isEmpty(ordersInfo.getExpressNo()) && !com.alibaba.excel.util.StringUtils.isEmpty(ordersInfo.getExpressCompanyNo())) {
                        orderInfoStatus = OrderStatusEnums.SHIPPED.getValue();
                    } else {
                        orderInfoStatus = OrderStatusEnums.UNSHIPPED.getValue();
                    }
                }
                FeiShuUtil.sendMsg(String.format("redis保存的原状态不存在或者6，系统已修复" + response.getOrdersInfoId()));
            }

            Integer integer = returnGoodsService.rollbackOrderStatus(response.getOrdersInfoId(), orderInfoStatus, response.getServiceNo(),response.getServiceDesc());
            if(integer != 1){
                FeiShuUtil.sendMsg(String.format("订单回到原状态出错，可能是供应链接口报错!,售后单id：%s",response.getId()));
                throw new ApiException("订单回到原状态出错！");
            }
            //修改销售端售后和订单的状态
            YxReturnGoods yxReturnGoodsRequest = new YxReturnGoods();
            yxReturnGoodsRequest.setServiceNo(response.getServiceNo());
            yxReturnGoodsRequest.setStatus(7);
            returnGoodsService.updateReturnGoods(yxReturnGoodsRequest);
        } catch (Exception e) {
            FeiShuUtil.sendMsg(String.format("订单售后类型【退货退款】超时未寄回，供应链订单状态回到原状态出错:%s,子订单id:%s",e.getMessage(),response.getOrdersInfoId()));
            log.error("订单售后类型【退货退款】超时未寄回，供应链订单状态回到原状态出错{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }
}
